package com.healthbox.appointmentservice.mapper;

import com.healthbox.appointmentservice.config.AppointmentConfig;
import com.healthbox.appointmentservice.entity.AppointmentLimit;
import com.healthbox.appointmentservice.mapper.AppointmentLimitMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.time.LocalDate;
import java.util.List;

/**
 * @author pengpeng
 * @date 2022/5/22
 * AppointmentLimitMapper的代理类，实际上只代理了一个方法numberOfAppointment(Long aLId)
 */
@Service
@Slf4j
public class LimitRepoProxy implements AppointmentLimitMapper {
    @Autowired
    private AppointmentLimitMapper appointmentLimitMapper;
    @Autowired
    private ValueOperations<String, Integer> appointmentNumberOps;
    @Autowired
    private AppointmentConfig config;

    @Override
    public int save(AppointmentLimit limit) {
        return appointmentLimitMapper.save(limit);
    }

    @Override
    public AppointmentLimit findOneById(Long aLId) {
        return appointmentLimitMapper.findOneById(aLId);
    }

    @Override
    public int update(AppointmentLimit limit) {
        return appointmentLimitMapper.update(limit);
    }

    @Override
    public Integer exists(String phone, Long aLId) {
        return appointmentLimitMapper.exists(phone, aLId);
    }

    @Override
    public int delete(Long aLId) {
        return appointmentLimitMapper.delete((aLId));
    }

    @Override
    public List<AppointmentLimit> findByDateAndHospitalId(LocalDate startDate, LocalDate endDate, Long hospitalId, Integer pageSize, Integer pageIndex) {
        return appointmentLimitMapper.findByDateAndHospitalId(startDate, endDate, hospitalId, pageSize, pageIndex);
    }

    // ---------------------------- 下面这两个方法有改变 -------------------------------
    @Override
    public int numberOfAppointment(Long aLId) {
        Integer n = appointmentNumberOps.get(config.getPrefix() + aLId);
        if (n!=null) {
            log.info("aLId=" + aLId + "的已预约数缓存命中: 预约人数:" + n);
            return n;
        }
        log.info("aLId=" + aLId + "的已预约数缓存未命中");
        n = appointmentLimitMapper.numberOfAppointment(aLId);
        appointmentNumberOps.set(config.getPrefix() + aLId, n, Duration.ofMinutes(config.getExpireTime()));
        return n;
    }

    @Override
    public void truncate() {
        appointmentLimitMapper.truncate();
    }
}
